package com.sh.data.engine.domain.management.service.Impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.data.engine.domain.base.model.PageResult;
import com.sh.data.engine.domain.management.model.domain.OperationLogDomain;
import com.sh.data.engine.domain.management.model.param.OperationLogQueryParam;
import com.sh.data.engine.domain.management.service.OperationService;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.repository.dao.management.operation.OperationsLogMapper;
import com.sh.data.engine.repository.dao.management.operation.entity.OperationsLogEntity;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;

@Slf4j
@Service
public class OperationServiceImpl extends ServiceImpl<OperationsLogMapper, OperationsLogEntity> implements OperationService {

    @Override
    public PageResult<OperationLogDomain> getLogPageList(OperationLogQueryParam param) {
        var lambdaQueryWrapper =
                new LambdaQueryWrapper<OperationsLogEntity>();
        lambdaQueryWrapper.eq(param.getOperationType() != null && !param.getOperationType().isEmpty(), OperationsLogEntity::getOperationType, param.getOperationType())
                .eq(param.getOperation() != null && !StringUtils.isEmpty(param.getOperation()), OperationsLogEntity::getOperation, param.getOperation())
                .eq(param.getModule() != null && !StringUtils.isEmpty(param.getModule()), OperationsLogEntity::getModule, param.getModule())
                .eq(param.getProjectName() != null && !StringUtils.isEmpty(param.getProjectName()), OperationsLogEntity::getProjectName, param.getProjectName())
                .eq(param.getDetailInfo() != null && !StringUtils.isEmpty(param.getDetailInfo()), OperationsLogEntity::getDetailInfo, param.getDetailInfo())
                .eq(param.getUserType() != null && !StringUtils.isEmpty(param.getUserType()), OperationsLogEntity::getUserType, param.getUserType())
                .eq(param.getOperator() != null && !StringUtils.isEmpty(param.getOperator()), OperationsLogEntity::getOperator, param.getOperator())
                .eq(param.getIpAddress() != null && !StringUtils.isEmpty(param.getIpAddress()), OperationsLogEntity::getIpAddress, param.getIpAddress())
                .eq(param.getOperationResult() != null && !StringUtils.isEmpty(param.getOperationResult()), OperationsLogEntity::getOperationResult, param.getOperationResult());

        IPage<OperationsLogEntity> logPage = this.page(new Page<>(param.getPageNum(), param.getPageSize()), lambdaQueryWrapper);
        PageResult<OperationsLogEntity> logPageResult = PageResult.convert(logPage);
        return ConvertUtil.convertPageInfo(logPageResult, OperationLogDomain.class);
    }


    @Override
    public void exportLogsToExcel(OperationLogQueryParam param, HttpServletResponse response) throws IOException {
        // 创建分页对象
        Page<OperationsLogEntity> page = new Page<>(param.getPageNum(), param.getPageSize());
        // 执行分页查询
        var lambdaQueryWrapper =
                new LambdaQueryWrapper<OperationsLogEntity>();
        lambdaQueryWrapper.eq(param.getOperationType() != null && !param.getOperationType().isEmpty(), OperationsLogEntity::getOperationType, param.getOperationType())
                .eq(param.getOperation() != null && !StringUtils.isEmpty(param.getOperation()), OperationsLogEntity::getOperation, param.getOperation())
                .eq(param.getModule() != null && !StringUtils.isEmpty(param.getModule()), OperationsLogEntity::getModule, param.getModule())
                .eq(param.getProjectName() != null && !StringUtils.isEmpty(param.getProjectName()), OperationsLogEntity::getProjectName, param.getProjectName())
                .eq(param.getDetailInfo() != null && !StringUtils.isEmpty(param.getDetailInfo()), OperationsLogEntity::getDetailInfo, param.getDetailInfo())
                .eq(param.getUserType() != null && !StringUtils.isEmpty(param.getUserType()), OperationsLogEntity::getUserType, param.getUserType())
                .eq(param.getOperator() != null && !StringUtils.isEmpty(param.getOperator()), OperationsLogEntity::getOperator, param.getOperator())
                .eq(param.getIpAddress() != null && !StringUtils.isEmpty(param.getIpAddress()), OperationsLogEntity::getIpAddress, param.getIpAddress())
                .eq(param.getOperationResult() != null && !StringUtils.isEmpty(param.getOperationResult()), OperationsLogEntity::getOperationResult, param.getOperationResult());

        Page<OperationsLogEntity> resultPage = this.baseMapper.selectPage(page, lambdaQueryWrapper);

        // 创建Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("日志数据");

        // 写入表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("详细信息");
        headerRow.createCell(2).setCellValue("IP地址");
        headerRow.createCell(3).setCellValue("所属模块");
        headerRow.createCell(4).setCellValue("操作");
        headerRow.createCell(5).setCellValue("操作类型");
        headerRow.createCell(6).setCellValue("操作结果");
        headerRow.createCell(7).setCellValue("操作时间");
        headerRow.createCell(8).setCellValue("用户");
        headerRow.createCell(9).setCellValue("所属项目");
        headerRow.createCell(10).setCellValue("用户类型");


        // 写入数据
        int rowIndex = 1;
        for (OperationsLogEntity log : resultPage.getRecords()) {
            Row dataRow = sheet.createRow(rowIndex++);
            dataRow.createCell(0).setCellValue(log.getId());
            dataRow.createCell(1).setCellValue(log.getDetailInfo());
            dataRow.createCell(2).setCellValue(log.getIpAddress());
            dataRow.createCell(3).setCellValue(log.getModule());
            dataRow.createCell(4).setCellValue(log.getOperation());
            dataRow.createCell(5).setCellValue(log.getOperationType());
            dataRow.createCell(6).setCellValue(log.getOperationResult());

            // 格式化日期
            CellStyle dateCellStyle = createDateCellStyle(workbook);
            Cell dateCell = dataRow.createCell(7);
            dateCell.setCellValue(log.getOperationTime());
            dateCell.setCellStyle(dateCellStyle);

            dataRow.createCell(8).setCellValue(log.getOperator());
            dataRow.createCell(9).setCellValue(log.getProjectName());
            dataRow.createCell(10).setCellValue(log.getUserType());
        }

        // 写入输出流并设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=operation_logs.xlsx");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        workbook.close();
        outputStream.flush();
        outputStream.close();
    }

    // 辅助方法：创建日期单元格样式
    private CellStyle createDateCellStyle(Workbook workbook) {
        CreationHelper createHelper = workbook.getCreationHelper();
        CellStyle style = workbook.createCellStyle();
        style.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
        style.setAlignment(HorizontalAlignment.LEFT);
        return style;
    }


}
